package algorithms.que13;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * @功能
 * @创建时间 2020/7/12
 */
public class Deque<Item> implements Iterable<Item>{
    Node last;
    Node first;
    Integer size;
    public boolean isEmpty(){
        return first==null;
    }
    public void addfirst(Item item){
        if(first.item==null){
            first=new Node();
            first.item=item;
            last=first;
        }else if(first.next==null){
            first=new Node();
            first.item=item;
            first.next=last;
            last.pre=first;
        }else if(first.next==last){
            Node oldfirst = new Node();
            oldfirst.item=first.item;
            oldfirst.next=first.next;
            oldfirst.pre=first;
            first.next=oldfirst;
            first.item=item;
            last.pre=oldfirst;
        }else {
            Node oldfirst = new Node();
            oldfirst.item=first.item;
            oldfirst.next=first.next;
            oldfirst.pre=first;
            first.next=oldfirst;
            first.item=item;
        }
        size++;
    }
    public Item delFirst(){
        Item item = first.item;
        if(first.next!=null){
        this.first=first.next;
        first.pre=null;}
        else {
            first.item=null;
        }
        size--;
        return item;
    }
    public void addlast(Item item){
        if(last.item==null){
            last=new Node();
            last.item=item;
            last=first;
        }else if(last.pre==null){
            last=new Node();
            last.pre=first;
            first.next=last;
            last.item=item;
        }else if(last.pre==first){
            Node oldLast = new Node();
            oldLast.pre=last.pre;
            oldLast.item=last.item;
            oldLast.next=last;
            last.item=item;
            last.pre=oldLast;
            first.next=oldLast;
        }else {
            Node oldLast = new Node();
            oldLast.pre=last.pre;
            oldLast.item=last.item;
            oldLast.next=last;
            last.item=item;
            last.pre=oldLast;
        }
        size++;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }
    private class ListIterator implements Iterator<Item>
    {
        private Node current=last.next;
        public boolean hasNext(){return current!=last.next;}
        public void remove(){}
        public Item next()
        {
            Item item=current.item;
            current=current.next;
            return item;
        }//end next
    }//end class ListIterato

    class Node{
        Item item;
        Node next;
        Node pre;
    }
}
